package com.yu.Demo01;

import java.util.concurrent.locks.ReentrantLock;

public class LockTicker {

    //通过lock来实现同步，保证爱不起
    private final ReentrantLock lock = new ReentrantLock();
    private int number = 30;
    private int count = 0;
    public  void sale(){
        lock.lock();
        try {
            if (number > 0){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出了" + (++count) + "还剩" + --number);
            }
        }catch (Exception e){

        }finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        LockTicker lockTicker = new LockTicker();
        new Thread(() ->{
            for (int i = 0; i <40 ; i++) {
                lockTicker.sale();
            }

        },"A").start();

        new Thread(() ->{
            for (int i = 0; i <40 ; i++) {
                lockTicker.sale();
            }
        },"B").start();

        new Thread(() ->{
            for (int i = 0; i <40 ; i++) {
                lockTicker.sale();
            }
        },"C").start();

    }

}
